<template>
  <div class="settings-content">
    <div class="content-header">
      <h2>Apple ID</h2>
      <p class="content-description">{{ isLoggedIn ? '管理您的 Apple ID 设置和服务' : '登录以使用 iCloud、App Store 等服务' }}</p>
    </div>

    <!-- 已登录状态 -->
    <div v-if="isLoggedIn" class="appleid-logged-in">
      <div class="user-profile">
        <div class="user-avatar">{{ userInfo.avatar }}</div>
        <div class="user-details">
          <h3 class="user-name">{{ userInfo.name }}</h3>
          <p class="user-email">{{ userInfo.email }}</p>
        </div>
      </div>

      <div class="account-sections">
        <div class="account-section">
          <h4 class="account-section-title">iCloud</h4>
          <div class="account-item">
            <div class="account-item-info">
              <span class="account-item-label">iCloud 云盘</span>
              <span class="account-item-value">5 GB（共 5 GB）</span>
            </div>
            <button class="account-item-btn">管理</button>
          </div>
          <div class="account-item">
            <div class="account-item-info">
              <span class="account-item-label">照片</span>
              <span class="account-item-value">已开启</span>
            </div>
            <button class="account-item-btn">选项</button>
          </div>
        </div>

        <div class="account-section">
          <h4 class="account-section-title">个人信息</h4>
          <div class="account-item">
            <div class="account-item-info">
              <span class="account-item-label">姓名、电话号码、电子邮件</span>
            </div>
            <button class="account-item-btn">管理</button>
          </div>
          <div class="account-item">
            <div class="account-item-info">
              <span class="account-item-label">密码与安全性</span>
            </div>
            <button class="account-item-btn">管理</button>
          </div>
          <div class="account-item clickable" @click="openLocationDialog">
            <div class="account-item-info">
              <span class="account-item-label">所在地区</span>
              <span class="account-item-value">{{ currentLocation }}</span>
            </div>
            <button class="account-item-btn">更改</button>
          </div>
        </div>

        <div class="account-section">
          <h4 class="account-section-title">设备</h4>
          <div class="account-item">
            <div class="account-item-info">
              <span class="account-item-label">MacBook Pro</span>
              <span class="account-item-value">此设备</span>
            </div>
            <button class="account-item-btn">详细信息</button>
          </div>
        </div>
      </div>

      <div class="account-actions">
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </div>

    <!-- 未登录状态 -->
    <div v-else class="appleid-login">
      <div class="login-card">
        <div class="login-header">
          <div class="apple-logo">🍎</div>
          <h3>登录以使用您的 Apple ID</h3>
          <p>一个 Apple ID 即可访问所有 Apple 服务</p>
        </div>

        <form @submit.prevent="handleLogin" class="login-form">
          <div class="form-group">
            <label for="email" class="form-label">Apple ID</label>
            <input
              id="email"
              type="email"
              v-model="loginForm.email"
              placeholder="name@example.com"
              class="form-input"
              :disabled="isLoggingIn"
            />
          </div>

          <div class="form-group">
            <label for="password" class="form-label">密码</label>
            <input
              id="password"
              type="password"
              v-model="loginForm.password"
              placeholder="输入密码"
              class="form-input"
              :disabled="isLoggingIn"
            />
          </div>

          <div v-if="loginError" class="login-error">
            {{ loginError }}
          </div>

          <button
            type="submit"
            class="login-submit-btn"
            :disabled="isLoggingIn"
          >
            {{ isLoggingIn ? '正在登录...' : '登录' }}
          </button>

          <div class="login-footer">
            <a href="#" class="login-link">忘记了 Apple ID 或密码？</a>
            <a href="#" class="login-link">创建 Apple ID</a>
          </div>
        </form>
      </div>

      <div class="login-info">
        <p class="info-text">💡 提示：这是模拟登录界面，输入任意邮箱和密码即可登录</p>
      </div>
    </div>

    <!-- 退出登录确认对话框 -->
    <ConfirmDialog
      :show="showLogoutConfirm"
      title="退出登录"
      message="确定要退出登录吗？\n\n退出后将清除所有缓存数据（包括锁屏密码），需要重新登录才能使用。"
      confirm-text="退出登录"
      cancel-text="取消"
      icon="⚠️"
      :is-danger="true"
      @confirm="confirmLogout"
      @cancel="cancelLogout"
    />

    <!-- 地区设置对话框 -->
    <transition name="macos-dialog-fade">
      <div v-if="showLocationDialog" class="macos-dialog-overlay" @click="showLocationDialog = false">
        <div class="macos-dialog macos-scale-in" @click.stop>
          <div class="macos-dialog-header">
            <h3 class="macos-dialog-title">设置所在地区</h3>
            <p class="macos-dialog-desc">设置您的所在地区，此信息将用于天气等应用</p>
          </div>
          
          <form @submit.prevent="handleSaveLocation" class="macos-dialog-content">
            <div class="macos-form-group">
              <label class="macos-form-label">省份</label>
              <input
                v-model="locationForm.province"
                type="text"
                class="macos-input"
                placeholder="例如：四川"
              />
            </div>
            
            <div class="macos-form-group">
              <label class="macos-form-label">城市</label>
              <input
                v-model="locationForm.city"
                type="text"
                class="macos-input"
                placeholder="例如：成都"
              />
            </div>
            
            <div class="macos-form-group">
              <label class="macos-form-label">区县</label>
              <input
                v-model="locationForm.county"
                type="text"
                class="macos-input"
                placeholder="例如：成华区"
              />
            </div>

            <div class="macos-dialog-actions">
              <button type="button" class="macos-button" @click="showLocationDialog = false">
                取消
              </button>
              <button type="submit" class="macos-button-primary" :disabled="!isLocationFormValid">
                保存
              </button>
            </div>
          </form>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useDesktopStore } from '../../../stores/desktop'
import ConfirmDialog from '../../common/ConfirmDialog.vue'

const desktopStore = useDesktopStore()

// 登录状态和用户信息直接从 store 获取
const isLoggedIn = computed(() => desktopStore.isLoggedIn)
const userInfo = computed(() => ({
  name: desktopStore.userAccount.username,
  email: desktopStore.userAccount.email,
  avatar: desktopStore.userAccount.avatar
}))

// 登录表单
const loginForm = ref({
  email: '',
  password: ''
})

const isLoggingIn = ref(false)
const loginError = ref('')
const showLogoutConfirm = ref(false)
const showLocationDialog = ref(false)

// 地区表单
const locationForm = ref({
  province: '',
  city: '',
  county: ''
})

// 当前地区显示
const currentLocation = computed(() => {
  const loc = desktopStore.userAccount.location
  return `${loc.province} ${loc.city} ${loc.county}`
})

// 地区表单验证
const isLocationFormValid = computed(() => {
  return locationForm.value.province.trim() && 
         locationForm.value.city.trim() && 
         locationForm.value.county.trim()
})

function handleLogin() {
  if (!loginForm.value.email || !loginForm.value.password) {
    loginError.value = '请输入 Apple ID 和密码'
    return
  }

  // 模拟登录过程
  isLoggingIn.value = true
  loginError.value = ''

  setTimeout(() => {
    // 使用 store 的登录方法
    const success = desktopStore.loginWithAppleID(loginForm.value.email, loginForm.value.password)
    
    if (success) {
      loginForm.value = { email: '', password: '' }
    } else {
      loginError.value = '登录失败，请重试'
    }
    
    isLoggingIn.value = false
  }, 1500)
}

function handleLogout() {
  showLogoutConfirm.value = true
}

function confirmLogout() {
  showLogoutConfirm.value = false
  desktopStore.logout()
}

function cancelLogout() {
  showLogoutConfirm.value = false
}

function handleSaveLocation() {
  if (!isLocationFormValid.value) return
  
  // 更新用户地区信息
  const success = desktopStore.updateUserLocation(
    locationForm.value.province.trim(),
    locationForm.value.city.trim(),
    locationForm.value.county.trim()
  )
  
  if (success) {
    showLocationDialog.value = false
    // 显示成功提示
    desktopStore.notify({
      title: '地区已更新',
      body: `已设置为 ${locationForm.value.province} ${locationForm.value.city} ${locationForm.value.county}`,
      icon: '📍',
      timeoutMs: 3000
    })
  }
}

// 打开地区对话框时初始化表单
function openLocationDialog() {
  const loc = desktopStore.userAccount.location
  locationForm.value = {
    province: loc.province,
    city: loc.city,
    county: loc.county
  }
  showLocationDialog.value = true
}
</script>

<style scoped>
/* macOS 现代化对话框 */
.macos-dialog-overlay {
  position: fixed;
  inset: 0;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  padding: 20px;
}

.macos-dialog {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(60px) saturate(200%);
  -webkit-backdrop-filter: blur(60px) saturate(200%);
  border-radius: 20px;
  padding: 0;
  width: 100%;
  max-width: 420px;
  border: 0.5px solid rgba(0, 0, 0, 0.1);
  box-shadow: 
    0 20px 60px rgba(0, 0, 0, 0.2),
    0 8px 32px rgba(0, 0, 0, 0.12),
    0 0 0 1px rgba(255, 255, 255, 0.8) inset;
}

.macos-dialog-header {
  padding: 24px 24px 20px 24px;
  border-bottom: 0.5px solid rgba(0, 0, 0, 0.08);
}

.macos-dialog-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 6px 0;
  color: #1d1d1f;
  letter-spacing: -0.01em;
}

.macos-dialog-desc {
  font-size: 13px;
  color: #86868B;
  margin: 0;
  line-height: 1.5;
  font-weight: 400;
}

.macos-dialog-content {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.macos-form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.macos-form-label {
  font-size: 13px;
  font-weight: 600;
  color: #1d1d1f;
  letter-spacing: -0.01em;
}

.macos-dialog-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.macos-dialog-actions button {
  flex: 1;
  height: 40px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.macos-dialog-actions button:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  transform: none !important;
}

.macos-dialog-actions button:disabled:hover {
  transform: none !important;
  box-shadow: 
    0 1px 2px rgba(0, 0, 0, 0.08),
    0 0 0 0.5px rgba(255, 255, 255, 0.5) inset !important;
}

/* 对话框动画 */
.macos-dialog-fade-enter-active {
  transition: opacity 0.3s cubic-bezier(0.32, 0.72, 0, 1);
}

.macos-dialog-fade-leave-active {
  transition: opacity 0.2s cubic-bezier(0.4, 0, 1, 1);
}

.macos-dialog-fade-enter-from,
.macos-dialog-fade-leave-to {
  opacity: 0;
}

.macos-dialog-fade-enter-active .macos-dialog {
  animation: macos-dialog-scale-in 0.35s cubic-bezier(0.32, 0.72, 0, 1);
}

@keyframes macos-dialog-scale-in {
  from {
    opacity: 0;
    transform: scale(0.92) translateY(20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 可点击项目 */
.account-item.clickable {
  cursor: pointer;
  transition: background 0.15s ease;
}

.account-item.clickable:hover {
  background: rgba(120, 120, 128, 0.08);
}

html.dark-mode .account-item.clickable:hover {
  background: rgba(255, 255, 255, 0.05);
}

/* 深色模式 */
html.dark-mode .macos-dialog {
  background: rgba(40, 40, 42, 0.75);
  border-color: rgba(255, 255, 255, 0.15);
  box-shadow: 
    0 20px 60px rgba(0, 0, 0, 0.6),
    0 8px 32px rgba(0, 0, 0, 0.4),
    0 0 0 1px rgba(255, 255, 255, 0.15) inset;
}

html.dark-mode .macos-dialog-header {
  border-bottom-color: rgba(255, 255, 255, 0.1);
}

html.dark-mode .macos-dialog-title {
  color: #f5f5f7;
}

html.dark-mode .macos-dialog-desc {
  color: #aeaeb2;
}

html.dark-mode .macos-form-label {
  color: #f5f5f7;
}

/* 响应式 */
@media (max-width: 480px) {
  .macos-dialog {
    max-width: 100%;
    border-radius: 20px;
  }
  
  .macos-dialog-header {
    padding: 20px 20px 16px 20px;
  }
  
  .macos-dialog-title {
    font-size: 18px;
  }
  
  .macos-dialog-content {
    padding: 20px;
    gap: 16px;
  }
}
</style>
